package com.lcq.shop.back.interceptor;

import java.net.URLEncoder;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lcq.shop.common.util.ConstatFinalUtil;
import com.lcq.shop.common.util.HttpUtil;
import com.lcq.shop.users.pojo.AAdmins;
import com.lcq.shop.users.service.IUsersService;

/**
 * 管理员登录的拦截器
 * 
 * @author ASUS-LCQ
 *
 */
@Component("loginAuthInterceptor")
public class LoginAuthInterceptor extends HandlerInterceptorAdapter
{
	@Resource
	private IUsersService usersService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
	{
		ConstatFinalUtil.LOGGER.info("-- 商城登录验证 --");
		HttpSession session = request.getSession();

		/* 从session中获取admins对象(从用户中心获取的管理员JSON对象) */
		AAdmins admins = (AAdmins) session.getAttribute("admins");
		if (admins != null)
		{
			/* 已经登陆 --- 放行 */
			return true;
		}
		/* 第一次登陆跳转和登陆成功后跳转,唯一不一样的是token,客户端是否需要跳转到用户中心登陆页面的标志就是:token */
		String token = request.getParameter("token");
		/* 取最后一个token */
		/*
		 * String[] tokens = request.getParameterValues("token"); token =tokens[tokens.length - 1] ;
		 */
		ConstatFinalUtil.LOGGER.info("--token:{}--", token);

		/* 验证Token的合法性 */
		String requestURL = ConstatFinalUtil.BUNDLE.getString("users.center.validatorTokenUrl");
		HttpUtil httpUtil = new HttpUtil();

		/* 拼装JSON,验证token需要的JSON */
		/*
		 * {"version":"1","data":{"token":"40639117-f3fd-4151-bbdb-c47fb54623bf"
		 * }}
		 */
		JSONObject requestJSON = new JSONObject();
		requestJSON.put("version", "1");
		JSONObject dataJSON = new JSONObject();
		dataJSON.put("token", token);
		requestJSON.put("data", dataJSON);
		try
		{
			Map<String, String> paramsMap = new HashMap<String, String>();
			paramsMap.put("json", requestJSON + "");
			String responseStr = httpUtil.methodPost(requestURL, Collections.EMPTY_MAP, paramsMap);
			ConstatFinalUtil.LOGGER.info("-验证-token返回:{}--", responseStr);
			JSONObject responseJSON = (JSONObject) JSON.parse(responseStr);
			/* 处理token */
			if ("0".equalsIgnoreCase(responseJSON.getString("code")))
			{
				/* 成功 */
				JSONObject dataResJSON = responseJSON.getJSONObject("data");
				if (dataResJSON.get("admins") != null)
				{
					/* token合法 */
					
					/* 将token对应的管理员信息放到session中 */
					JSONObject adminsJSON = (JSONObject) dataResJSON.get("admins");
					adminsJSON.put("token", token);

					/* 从session中取数据,储存到数据库中去 */
					/* 将JSON转换为管理员对象 */
					
					/* 如果是第一次登陆,就new一个对象,如果是第二次登陆,从数据库查询吧
					 * 先查询数据库
					 *  */
					Map<String, Object> condMap = new HashMap< String, Object>();
					/*从用户中心返回的JSON中获取id,也就是商城中管理员的ssoId*/
					condMap.put("ssoId", adminsJSON.get("id"));
					admins = this.usersService.findOneAdminsService(condMap);
					/*一开始先默认为更新*/
					boolean updateFlag = true;
					if(admins == null)
					{
						admins = new AAdmins();
						admins.setCreateTime(new Date());
						/*如果admins为null,再改为false,要插入*/
						updateFlag = false;
					}
					admins = admins.parseObject(adminsJSON);
					/* 只有上次登录时间有用 */
					admins.setUpdateTime(new Date());
					if(updateFlag)
					{
						this.usersService.updateOneAdminsService(admins);
					}else
					{
						/* 存储数据库 */
						this.usersService.saveOneAdminsService(admins);
					}

					session.setAttribute("admins", admins);
					return true;
				}
			}
		} catch (Exception e)
		{
		}

		/* 获取returnUrl:当前即将访问的url */
		String returnUrl = request.getRequestURL() + "";
		/* 获取?后面的内容 */
		String queryStr = request.getQueryString();
		if (queryStr == null)
		{
			queryStr = "";
		}

		/* 拼装returnUrl */
		if (queryStr.length() > 0)
		{
			returnUrl = returnUrl + "?" + queryStr;
		}
		ConstatFinalUtil.LOGGER.info("--currUrl:{}--queryStr:{}", returnUrl, queryStr);

		/* 跳转到用户中心的登陆页面,并且将returnUrl带上去 */
		String usersCenterLoginUrl = ConstatFinalUtil.BUNDLE.getString("users.center.loginUrl") + "&returnUrl="
				+ URLEncoder.encode(returnUrl, "UTF-8");
		ConstatFinalUtil.LOGGER.info("--usersCenterLoginUrl:{}", usersCenterLoginUrl);
		/* 客户端跳转 */
		response.sendRedirect(usersCenterLoginUrl);

		return false;
	}

}
